﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections;

namespace Quebec.Silverlight.AttachedProperties
{
	public static class LocalizedStrings
	{
		public static readonly DependencyProperty KeyProperty = DependencyProperty.RegisterAttached(
			"ResourceKey",
			typeof(string),
			typeof(LocalizedStrings),
			new PropertyMetadata(null, new PropertyChangedCallback(OnResourceKeyChanged))
		);

		private static void OnResourceKeyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
		{
			UIElement obj = sender as UIElement;

			if (obj == null ||
				Application.Current.Resources.Contains("LocalizedStrings") == false)
			{
				return;
			}

			string key = e.NewValue as string;

			IDictionary dict = Application.Current.Resources["LocalizedStrings"] as IDictionary;

			string value = key;
			if (dict != null && dict.Contains(key))
			{
				value = dict[key].ToString();
			}

			if (obj is TextBlock)
			{
				((TextBlock)obj).Text = value;
			}
			else if (obj is ContentControl)
			{
				((ContentControl)obj).Content = value;
			}
		}

		public static void SetResourceKey(UIElement obj, string value)
		{
			obj.SetValue(KeyProperty, value);
		}

		public static string GetResourceKey(UIElement obj)
		{
			return obj.GetValue(KeyProperty) as string;
		}
	}
}
